package com.tsxy.common.intercepter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Date;


@Aspect
@Component
public class WebLogAspect{

    private static final  Logger logger = LoggerFactory.getLogger(WebLogAspect.class);

    @Pointcut("execution(public * com.tsxy.controller..*.*(..))")
    public void webLog() {
    }

//    @Autowired
//    private CcnpOpLogMapper logMapper;
//    @Autowired
//    private CcnpOpLogContentMapper ccnpOpLogContentMapper;
    /*@Pointcut("@annotation(com.channelsoft.dcmsx.annotion.OpLog)")
    public void opLogPointCut(){

    }*/

    @Around("webLog()")
    public Object doAroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        // 接收到请求，记录请求内容
        long start = System.currentTimeMillis();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        StringBuilder sb = new StringBuilder();
        sb.append("调用URL:[" + request.getRequestURL().toString() + "]," +
                "调用方法为:[" +proceedingJoinPoint.getSignature().getDeclaringTypeName() + "." + proceedingJoinPoint.getSignature().getName() + "],args=[");
        for (Object o : proceedingJoinPoint.getArgs()) {
            if (o == null || o instanceof  HttpServletRequest  || o instanceof HttpServletResponse) {
                continue;
            }
            sb.append(o.toString() + ",");
        }
        sb.append("]");
        logger.info(sb.toString());
        Object obj = proceedingJoinPoint.proceed();
        long end = System.currentTimeMillis();
        logger.info("调用时间：[" + (end - start) + "].");
        return obj;
    }



    /**
     * 获取用户真实的ip地址，不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真是的ip
     * 可是如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串ip值，究竟哪个是真是的值，答案是
     * 取X-Forwarded-For中第一个非unknown的有效ip字符串
     * @param request
     */
    public String getIpAddress(HttpServletRequest request){
        String ip=request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip=request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
